<script setup lang="ts">
import { reactive, getCurrentInstance } from "vue";

import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import upload from "@iconify-icons/ep/upload";
import Refresh from "@iconify-icons/ep/refresh";
import { Plus } from "@element-plus/icons-vue";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from "element-plus";
import AppUtil from "@/utils/AppUtil";

import AddFill from "@iconify-icons/ri/add-circle-line";
import { useRoute } from "vue-router";
import Edit from "@iconify-icons/ep/edit";
//import log from "./comp/log.vue";
import Form from "@/components/Form.vue";
import { stat } from "node:fs";
const route = useRoute();
defineOptions({
  name: "users"
});
const config = reactive({
  listUrl: "/api/v1/stores/goods",
  addUrl: "",
  editUrl: "",
  deleteUrl: "",
  detailUrl: "",
  title: "库存",

  /**搜索条件 */
  searchForm: [
    {
      label: "商品条形码",
      prop: "barCode",
      type: "input",
      input: {
        type: "text"
      }
    },
    {
      label: "商品",
      prop: "goodsName",
      type: "input",
      input: {
        type: "text"
      }
    },
    //门店 storeName
    {
      label: "门店",
      prop: "storeName",
      type: "select",

      select: {
        placeholder: "请选择门店",
        options: [],
        filterable: true,
        remote: true,
        loading: false,
        remoteMethod(query, val) {
          // console.log("remoteMethod", query, val);
          AppUtil.request(
            {
              url: "/api/v1/stores?size=10",
              method: "get",
              params: {
                storesName: query || ""
              }
            },
            (res: any) => {
              res.data.records.map(item => {
                item.value = item.storesName;
                item.name = item.storesName;
              });
              val.options = val.select.options = res.data.records;
              // console.log("remoteMethod", res.data)
            },
            b => {
              val.select.loading = false;
            }
          );

          // if (!val.options || !val.options.length) {
          //   val.select.loading = true;

          // } else if (query) {
          //   val.select.options = val.options.filter((val) => {
          //     return val.name.includes(query);
          //   });
          // } else {
          //   val.select.options = val.options;
          // }
        }
      }
    },
    //status 状态
    {
      label: "状态",
      prop: "storeGoodStatus",
      type: "select",
      select: {
        placeholder: "请选择状态",
        options: [
          {
            label: "已上架",
            value: "0"
          },
          {
            label: "已下架",
            value: "1"
          }
        ]
      }
    }
    // {
    //   label: "门店",
    //   prop: "storeName",
    //   type: "input",
    //   input: {
    //     type: "text"
    //   }
    // }
  ],
  /**
   * 添加/编辑表单
   */
  editForm: [],
  rules: {},
  formData: {} as any,
  defaultData: {},

  /**
   * 表格列
   */
  columns: [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "商品id",
      prop: "goodsId",
      width: 100
    },
    {
      label: "商品",
      prop: "goodsName"
    },
    {
      label: "门店id",
      prop: "storeId",
      width: 100
    },
    {
      label: "门店",
      prop: "storesName"
    },
    //  {
    //   label: "价格",
    //   prop: "price",
    //   width: 150
    // },
    {
      label: "库存",
      prop: "stock",
      slot: "stock",
      width: 180
    },

    {
      label: "操作",
      prop: "action",
      width: 150,
      slot: "operation"
    }
  ]
});

const pData = reactive({
  /**
   * 表格数据
   */
  dataArr: [],
  /**
   * 表格加载
   */
  loading: false,
  /**请求中 */
  reqing: false,
  /**
   * 表格分页
   */
  pagination: {
    total: 0,
    pageSize: 50,
    currentPage: 1,
    background: true
  },

  searchData: {
    storeGoodStatus: "0"
  },
  showEdit: false,

  id: "",
  // item: {},
  showStock: false,
  stock: {
    editForm: [
      // 门店 storeSid
      {
        label: "门店",
        prop: "storeSid",
        type: "select",
        select: {
          placeholder: "请选择门店",
          options: [],
          filterable: true,
          remote: true,
          loading: false,
          remoteMethod(query, val) {
            // console.log("remoteMethod", query, val);

            if (!val.options || !val.options.length) {
              val.select.loading = true;
              AppUtil.request(
                {
                  url: "/api/v1/stores",
                  method: "get"
                },
                (res: any) => {
                  res.data.records.map(item => {
                    item.value = item.sid;
                    item.name = item.storesName;
                  });
                  val.options = val.select.options = res.data.records;
                  // console.log("remoteMethod", res.data)
                },
                b => {
                  val.select.loading = false;
                }
              );
            } else if (query) {
              val.select.options = val.options.filter(val => {
                return val.name.includes(query);
              });
            } else {
              val.select.options = val.options;
            }
          }
        },
        rules: [
          {
            required: true,
            message: "请选择门店",
            trigger: "change"
          }
        ]
      },
      //库存 stock
      {
        label: "库存",
        prop: "stock",
        type: "input",
        input: {
          type: "number"
        },
        rules: [
          {
            validator: (rule: any, value: any, callback: any) => {
              if (value < 0) {
                return callback(new Error("库存必须大于等于0"));
              }
              callback();
            }
          }
        ]
      }
    ],
    formData: {} as any,
    defaultData: {}
  },
  /**角色列表 */
  roleArr: [],

  /**选中的商品 */
  selectArr: []
});

const instance = getCurrentInstance();

function update_click(item) {
  AppUtil.request(
    {
      url: "/api/v1/stores/" + item.goodsId + "/status/" + item.storeId,
      method: "put"
    },
    res => {
      console.log("banner", res);
      instance.proxy.$message.success("修改成功");
      onSearch();
      // pData.showEdit = false;
    }
  );
}

//请求轮播图数据
async function onSearch() {
  pData.loading = true;

  AppUtil.request(
    {
      url: config.listUrl,
      method: "get",
      params: {
        ...pData.searchData,
        current: pData.pagination.currentPage,
        size: pData.pagination.pageSize
      }
    },
    res => {
      // console.log("onSearch", res);

      res.data.records.map(item => {
        item.stock0 = item.stock;
      });
      pData.dataArr = res.data.records;
      pData.pagination.total = res.data.total * 1;
      pData.pagination.currentPage = res.data.current * 1;
    },
    b => (pData.loading = false)
  );
}

onSearch();

function search_click() {
  reset_list();
}
/**搜索第一页的数据 */
function reset_list() {
  pData.pagination.currentPage = 1;
  onSearch();
}
function submitForm() {
  submit_form();
  // if (pData.imgArr.length < 1) {
  //   return instance.proxy.$alert("请选择图片");
  // }
  // let img = pData.imgArr[0];
  // //图片已经上传过
  // if (img.response && img.response.code == 200) {
  //   return submit_form();
  // }
  // //上传图片
  // upload1.value!.submit();
}
/**
 * 提交表单
 */
function submit_form() {
  // instance.proxy.$refs["vForm"].validate(valid => {
  // if (!valid) return;
  pData.reqing = true;
  let arr = [];
  pData.dataArr.map(item => {
    // if (item.status != 0) {
    //   item.stock = 0;
    // }
    if (item.stock0 != item.stock) {
      arr.push({
        goodsId: item.goodsId,
        stock: item.stock,
        storeId: item.storeId
      });
    }
  });

  // return console.log("submit!", arr);
  // return console.log("formData", config.formData);
  //config.formData 移除sid
  // let formData: any = JSON.parse(JSON.stringify(config.formData));
  // delete formData.sid;

  // formData.label = lArr;

  AppUtil.request(
    {
      url: "/api/v1/stores/goods/stock",

      method: "post",
      // url: config.addUrl,
      // method: "post",
      // data: formData
      data: {
        goodsStockList: arr
      }
    },
    res => {
      console.log("banner", res);
      instance.proxy.$message.success("修改成功");
      onSearch();
      // pData.showEdit = false;
    },
    b => {
      pData.reqing = false;
    }
  );
  // });
}
const handleSelectionChange = val => {
  console.log("handleSelectionChange", val);
  pData.selectArr = val;
};
function status_click(status: number) {
  let goodsStoreList = [];
  pData.selectArr.map(item => {
    goodsStoreList.push({
      goodsId: item.goodsId,
      storeId: item.storeId
    });
  });
  AppUtil.request(
    {
      url: "/api/v1/stores/store-status",
      method: "post",
      data: {
        goodsStoreList: goodsStoreList,
        status: status
      }
    },
    res => {
      console.log("banner", res);
      instance.proxy.$message.success("修改成功");
      onSearch();
      // pData.showEdit = false;
    }
  );
}
</script>

<template>
  <div class="main">
    <el-form
      v-if="config.searchForm && config.searchForm.length > 0"
      :model="pData.searchData"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
      style="padding-bottom: 5px"
      :inline="true"
    >
      <el-form-item
        v-for="(item, i) in config.searchForm"
        :key="i"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-if="item.type == 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          :multiple="item.select?.multiple || false"
          :placeholder="item.select?.placeholder"
          clearable
          :remote-method="q => item.select?.remoteMethod(q, item)"
          remote-show-suffix
          filterable
          :remote="item.select?.remote || false"
          :loading="item.select?.loading || false"
        >
          <el-option
            v-for="(item2, index2) in item.select.options"
            :key="index2"
            :label="item2.label || item2.name"
            :value="item2.value || item2.id"
          />
        </el-select>
        <!-- <el-select
          v-if="item.type === 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="(option, j) in item.options"
            :key="j"
            :label="option.label || option.name"
            :value="option.value || option.id"
          />
        </el-select> -->
        <el-input
          v-else-if="item.type === 'input'"
          v-model="pData.searchData[item.prop]"
          :placeholder="item.input.placeholder"
          clearable
        />
        <el-date-picker
          v-else-if="item.type === 'datetimerange'"
          v-model="pData.searchData[item.prop]"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 360px"
        />
        <el-cascader
          v-else-if="item.type === 'cascader'"
          v-model="pData.searchData[item.prop]"
          style="width: 100%"
          :props="item.cascader.props"
          :options="item.cascader.options"
          clearable
          :placeholder="item.cascader.placeholder"
          :show-all-levels="item.cascader.showAllLevels || false"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="pData.loading"
          @click="search_click"
        >
          搜索
        </el-button>
      </el-form-item>
    </el-form>
    <pure-table
      empty-text="请进行筛选"
      style="margin: 1rem 0"
      :data="pData.dataArr"
      :columns="config.columns"
      :loading="pData.loading"
      border
      @selection-change="handleSelectionChange"
    >
      <template #stock="{ row }">
        <el-input-number v-model="row.stock" :min="0" :max="99999999" />
      </template>

      <template #operation="{ row }">
        <el-button
          class="reset-margin"
          link
          :type="row.status == 0 ? 'primary' : 'danger'"
          @click="update_click(row)"
        >
          {{ row.status == 0 ? "下架" : "上架" }}
        </el-button>

        <!-- <el-popconfirm
          :title="`是否确认删除这条数据`"
          @confirm="handleDelete(row)"
        >
          <template #reference>
            <el-button class="reset-margin" link type="primary" :size="size">
              删除
            </el-button>
          </template>
        </el-popconfirm> -->
      </template>
    </pure-table>
    <div class="search-form bg-bg_color w-[99/100] pr-8 pt-3 pb-3 cls-end">
      <!-- 批量上架 -->
      <el-button
        v-if="pData.selectArr.length > 0"
        type="success"
        :icon="useRenderIcon('ri:upload-2-fill')"
        :loading="pData.reqing"
        @click="status_click(0)"
      >
        批量上架
      </el-button>
      <el-button
        v-if="pData.selectArr.length > 0"
        type="warning"
        :icon="useRenderIcon('ri:download-2-fill')"
        :loading="pData.reqing"
        @click="status_click(1)"
      >
        批量下架
      </el-button>

      <el-button
        type="primary"
        :icon="useRenderIcon('ri:upload-2-fill')"
        :loading="pData.reqing"
        @click="submit_form"
      >
        提交修改
      </el-button>
    </div>
    <!-- <el-dialog
      v-model="pData.showEdit"
      align-center
      :title="`${config.formData.sid ? '修改' : '新增'}${config.title}`"
      :width="700"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="vForm" v-model="config" />
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showEdit = false">取消</el-button>
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitForm()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog> -->
    <!-- <el-dialog
      v-model="pData.showStock"
      align-center
      title="录入库存"
      width="600px"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="sForm" v-model="pData.stock" />
      </div>
      <template #footer>
        <div class="cls-center">
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitStockForm()"
          >
            确定
          </el-button>
          <el-button @click="pData.showStock = false">关闭</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
